﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq.Expressions;
using System.Web.Mvc;
using AFT.Parking.Bizlogic.ConstructionInfo;
using AFT.Parking.Entity;
using AFT.Parking.Entity.ArgumentEntity;
using AFT.Parking.Foundation.Utilities;
using AFT.Parking.WebSite.Common;
using AFT.Parking.WebSite.Filter;
using ICSharpCode.SharpZipLib.Zip;
using Newtonsoft.Json;
using FileHelper = AFT.Parking.WebSite.Common.FileHelper;

namespace AFT.Parking.WebSite.Controllers
{
    public class MaterialController:BaseController
    {
        private readonly ConstructionInfoBiz _constructionInfoBiz;

        public MaterialController()
        {
            _constructionInfoBiz=new ConstructionInfoBiz();
        }

        [AdminOnly]
        [HttpGet]
        public ActionResult MaterialInfoRegister(int id = 0)
        {
            var result = id == 0 ? new MaterialRecord() : _constructionInfoBiz.GetById<MaterialRecord>(id);
            return View(result);
        }

        [AdminOnly]
        [HttpPost]
        public ActionResult MaterialInfoRegister(MaterialRecord record)
        {
            ValidateSercurityModel(record);
            return View(record);
        }

        [AdminOnly]
        [HttpGet]
        public ActionResult MaterialRecordList(string name, int page = 1)
        {
            Expression<Func<MaterialRecord, bool>> exp = u => true;
            if (!string.IsNullOrEmpty(name))
            {
                exp = u => u.MaterialName.Contains(name);
            }
            var p = new PaginationParam<MaterialRecord>
            {
                Expression = exp,
                PageSize = 20,
                PageIndex = page,
                OrderByList = new List<OrderBy<MaterialRecord>>
                    {
                        new OrderBy<MaterialRecord> {Sort = false, exp = u => u.UpdateTime}
                    }
            };
            var list = _constructionInfoBiz.GetList<MaterialRecord>(p);
            return View(list);
        }

        [AdminOnly]
        [HttpPost]
        public ActionResult UpLoadFile(string folderName)
        {
            var result = FileHelper.Upload(folderName);
            return Content(JsonConvert.SerializeObject(result));
        }


        [AdminOnly]
        [HttpGet]
        public ActionResult Delete(int id)
        {
            var delItem = _constructionInfoBiz.Remove<MaterialRecord>(id);
            var qrcodeImg = Server.MapPath(delItem.ImgUrl);
            if (System.IO.File.Exists(qrcodeImg))
            {
                System.IO.File.Delete(qrcodeImg);
            }
            return Json(true, JsonRequestBehavior.AllowGet);
        }

        [AdminOnly]
        [HttpPost]
        public ActionResult UpLoadExcel(string folderName)
        {
            var temp = FileHelper.Upload(folderName);
            var tempResult = temp.Result as string[];
            if (tempResult != null)
            {
                var filePath = FileHelper.Save("ConstructionExcel", tempResult[0]);
                var path = Server.MapPath(filePath);
                if (string.IsNullOrEmpty(path))
                {
                    return Content(JsonConvert.SerializeObject(new BoolResult
                    {
                        Value = false,
                        Message = "文件上传失败"
                    }));
                }

                var result = _constructionInfoBiz.ParseMaterialExcel(path);
                return Content(JsonConvert.SerializeObject(new BoolResult
                {
                    Value = result,
                    Message = result ? "上传成功" : "文件解析失败"
                }));
            }
            return Content(JsonConvert.SerializeObject(new BoolResult
            {
                Value = false,
                Message = "上传失败"
            }));
        }

        [AdminOnly]
        [HttpGet]
        public ZipResult ZipQrCode()
        {
            const int zipConvertLevel = 6;
            var folder = Server.MapPath("/Upload/Material");

            using (var ms = new MemoryStream())
            {
                using (var zipstr = new ZipOutputStream(ms))
                {
                    zipstr.SetLevel(zipConvertLevel);
                    var files = Directory.GetFileSystemEntries(folder);
                    foreach (var fileName in files)
                    {
                        using (var fs = System.IO.File.OpenRead(fileName))
                        {
                            var buffer = new byte[fs.Length];
                            fs.Read(buffer, 0, buffer.Length);

                            var entry = new ZipEntry(fileName.Substring(fileName.LastIndexOf("\\", StringComparison.Ordinal) + 1));
                            zipstr.PutNextEntry(entry);
                            zipstr.Write(buffer, 0, buffer.Length);
                            fs.Flush();
                            fs.Position = 0;
                            fs.Close();
                        }
                    }
                    zipstr.Finish();
                    ms.Position = 0;

                    return new ZipResult(ms)
                    {
                        FileDownloadName = "机械设备二维码.zip"
                    };
                }
            }
        }

        [AllowAnonymous]
        [HttpGet]
        public ActionResult ScanView(string tagId)
        {
            var record = _constructionInfoBiz.GetMaterialByTagId(tagId);
            return View(record);
        }

        #region private actions
        private void ValidateSercurityModel(MaterialRecord record)
        {
            var msg = string.Empty;
            var icon = "error";
            if (string.IsNullOrEmpty(record.MaterialName))
            {
                msg += "标题不能为空";
            }
            if (string.IsNullOrEmpty(record.TagName))
            {
                msg += "二维码名称不能为空";
            }
            if (msg.Length == 0)
            {
                record.TagId = record.TagId ?? Guid.NewGuid().ToString();
                record.ImgUrl = QrCodeHelper.GenerateQrcode("Material", record.TagId, record.TagName);
                if (_constructionInfoBiz.SaveMaterialRecord(record))
                {
                    icon = "success";
                    msg = "保存成功。";
                }
                else
                {
                    msg = "保存失败，存在相同的信息。";
                }
            }
            ViewBag.Message = msg;
            ViewBag.Icon = icon;
        }
        #endregion
    }
}